$(function () {
    $('#topBtn').click(setTop);
    $('#refineBtn').click(setRefine);
    $('#deleteBtn').click(setDelete);
});

function like(btn, entityType, entityId, entityAuthorId, discussPostId) {

    // 发送 AJAX 请求之前，将 CSRF 令牌设置到请求消息头中
    var token = $("meta[name='_csrf']").attr("content");
    var header = $("meta[name='_csrf_header']").attr("content");
    $(document).ajaxSend(function (e, xhr, options) {
        xhr.setRequestHeader(header, token);
    });

    $.post(
        CONTEXT_PATH + "/like",
        {"entityType":entityType, "entityId":entityId, "entityAuthorId":entityAuthorId, "discussPostId":discussPostId},
        function (data) {
            console.log(data);
            data = $.parseJSON(data);
            if(data.code === 200){
                $(btn).children("i").text(data.likeCount);
                $(btn).children("b").text(data.likeStatus === 1 ? '已赞' : '赞');
            }else{
                alert(data.msg);
            }
        }
    );
}

// 将帖子置顶
function setTop() {
    // 发送 AJAX 请求之前，将 CSRF 令牌设置到请求消息头中
    var token = $("meta[name='_csrf']").attr("content");
    var header = $("meta[name='_csrf_header']").attr("content");
    $(document).ajaxSend(function (e, xhr, options) {
        xhr.setRequestHeader(header, token);
    });

    $.post(
        CONTEXT_PATH + "/discussPost/top",
        {"discussPostId":$('#discussPostId').val()},
        function (data) {
            data = $.parseJSON(data);
            if(data.code === 200){
                $('#topBtn').attr("disabled", "disabled");
            }else{
                alert(data.msg);
            }
        }
    );
}

// 将帖子加精
function setRefine() {
    // 发送 AJAX 请求之前，将 CSRF 令牌设置到请求消息头中
    var token = $("meta[name='_csrf']").attr("content");
    var header = $("meta[name='_csrf_header']").attr("content");
    $(document).ajaxSend(function (e, xhr, options) {
        xhr.setRequestHeader(header, token);
    });

    $.post(
        CONTEXT_PATH + "/discussPost/refine",
        {"discussPostId":$('#discussPostId').val()},
        function (data) {
            data = $.parseJSON(data);
            if(data.code === 200){
                $('#refineBtn').attr("disabled", "disabled");
            }else{
                alert(data.msg);
            }
        }
    );
}

// 将帖子删除
function setDelete() {
    // 发送 AJAX 请求之前，将 CSRF 令牌设置到请求消息头中
    var token = $("meta[name='_csrf']").attr("content");
    var header = $("meta[name='_csrf_header']").attr("content");
    $(document).ajaxSend(function (e, xhr, options) {
        xhr.setRequestHeader(header, token);
    });

    $.post(
        CONTEXT_PATH + "/discussPost/delete",
        {"discussPostId":$('#discussPostId').val()},
        function (data) {
            data = $.parseJSON(data);
            if(data.code === 200){
                location.href = CONTEXT_PATH + "/index";
            }else{
                alert(data.msg);
            }
        }
    );
}